package com.charles.seckillPlatform.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class SentinelRulesInitializer {

    public final static Logger logger = LoggerFactory.getLogger(SentinelRulesInitializer.class);

    @PostConstruct
    public void initSentinelRules() {
        List<FlowRule> rules = new ArrayList<>();

        // 全局限流
        FlowRule globalRule = new FlowRule();
        globalRule.setResource("GlobalResource");
        globalRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        globalRule.setCount(1000);
        rules.add(globalRule);
        
        // 秒杀 API 限流
        FlowRule seckillRule = new FlowRule();
        seckillRule.setResource("seckillGood");
        seckillRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        seckillRule.setCount(400);
        rules.add(seckillRule);

        // 访问令牌生成限流
        FlowRule genTokenRule = new FlowRule();
        genTokenRule.setResource("generateToken");
        genTokenRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        genTokenRule.setCount(500);
        rules.add(genTokenRule);

        try {
            FlowRuleManager.loadRules(rules);
            logger.info("限流服务已启动");
        } catch (Exception e) {
            logger.error("加载限流规则失败: ", e);
        }
    }

}
